package com.forsir.android.mhfinance;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.forsir.android.mhfinance.helper.DbAdapter;
import com.forsir.android.mhfinance.helper.ManageExpandableItemActivity;
import com.forsir.android.mhfinance.storeObjects.Category;
import com.forsir.android.mhfinance.storeObjects.CategoryList;
import com.forsir.android.mhfinance.storeObjects.IStorable;
import com.forsir.android.mhfinance.storeObjects.Payment;
import com.forsir.android.mhfinance.storeObjects.Repeating;
import com.forsir.android.mhfinance.storeObjects.Subcategory;

public class SelectCategory extends ManageExpandableItemActivity {
	public final static String REQUEST_SELECTED_CATEGORY_ID = "selected_category_id";
	public final static String REQUEST_ALL_CATEGORIES = "all_categories";
	public final static String RETURN_SELECTED_CATEGORY_ID = "selected_category_id";
	public final static String RETURN_CATEGORY_POSITION = "category_position";
	public final static String RETURN_SUBCATEGORY_POSITION = "subcategory_position";

	protected ExpandableListView categoriesListView;
	protected boolean allCategories = false;

	public void onSuperCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_category);
		// setTheme(android.R.style.Widget_ListView_Menu);

		categoriesListView = (ExpandableListView) findViewById(R.id.select_category);
		registerForContextMenu(categoriesListView);

		if (savedInstanceState != null) {
			allCategories = savedInstanceState.getBoolean(REQUEST_ALL_CATEGORIES, false);
		} else {
			final Bundle extras = getIntent().getExtras();
			if (extras != null) {
				allCategories = extras.getBoolean(REQUEST_ALL_CATEGORIES, false);
				lastMenuChildPos = CategoryList.getSubcategoryParentPosById(extras.getLong(SelectCategory.REQUEST_SELECTED_CATEGORY_ID, -1));
			}
		}

		fillCategoryData();
		if (!allCategories) {
			categoriesListView.setOnItemLongClickListener(itemLongClickListener);
		}
		categoriesListView.setOnChildClickListener(onChildClickListener);
		categoriesListView.setOnGroupClickListener(groupClickListener);
	}

	protected void fillCategoryData() {
		Category newCategory = new Category(getString(R.string.menu_category_new));
		Subcategory newSubcategory = new Subcategory(getString(R.string.menu_subcategory_new));
		boolean onlyIfEmpty = false;

		if (mAddNewType.contentEquals("ever")) {
			onlyIfEmpty = false;
		} else if (mAddNewType.contentEquals("empty")) {
			onlyIfEmpty = true;
		} else if (mAddNewType.contentEquals("never")) {
			newSubcategory = null;
			onlyIfEmpty = true;
		}

		if (allCategories) {
			newCategory = new Category(getString(R.string.all_categories));
			newSubcategory = null;
			onlyIfEmpty = false;
		}

		final SimpleExpandableListAdapter categories = new SimpleExpandableListAdapter(this, CategoryList.getMainGroup(newCategory, onlyIfEmpty),
		        android.R.layout.simple_expandable_list_item_1, new String[] { "name" }, new int[] { android.R.id.text1 }, CategoryList.getChildGroup(newSubcategory,
		                onlyIfEmpty), android.R.layout.simple_expandable_list_item_2, new String[] { "name" }, new int[] { android.R.id.text1 });

		categoriesListView.setAdapter(categories);
		if (lastMenuChildPos >= 0) {
			categoriesListView.expandGroup(lastMenuChildPos);
		}
	}

	protected OnItemLongClickListener itemLongClickListener = new OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			// Category category = mCategoryList.getCategoryAtAbsolute(position, true);
			return false;
		}
	};

	OnChildClickListener onChildClickListener = new OnChildClickListener() {
		public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
			final Subcategory subcategory = CategoryList.getSubcategory(groupPosition, childPosition);
			if (subcategory != null) {
				final Intent data = new Intent();

				data.putExtra(SelectCategory.RETURN_SELECTED_CATEGORY_ID, CategoryList.getSubcategory(groupPosition, childPosition).getId());
				data.putExtra(SelectCategory.RETURN_CATEGORY_POSITION, groupPosition);
				data.putExtra(SelectCategory.RETURN_SUBCATEGORY_POSITION, childPosition);

				SelectCategory.this.setResult(Activity.RESULT_OK, data);
				SelectCategory.this.finish();
			} else {
				final Category category = CategoryList.getCategory(groupPosition);
				parentItemId = category.getId();
				addNewSubCategory();
			}
			return false;
		}
	};

	protected final OnGroupClickListener groupClickListener = new OnGroupClickListener() {
		public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
			final Category category = CategoryList.getCategory(groupPosition);
			if (category == null) {
				if (allCategories) {
					final Intent data = new Intent();
					SelectCategory.this.setResult(Activity.RESULT_OK, data);
					SelectCategory.this.finish();
					return true;
				}

				addNewItem(new Category());
				return true;
			}
			return false;
		}
	};

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		final ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;

		final int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			final int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			final int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
			if (!CategoryList.isAddNew(groupPos, childPos)) {
				final MenuInflater inflater = getMenuInflater();
				inflater.inflate(R.menu.menu_subcategory, menu);
			}
		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			final MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu_category, menu);
		}
	}

	@Override
	protected void processAddNewItem(String name) {
		final Category category = new Category();
		category.setName(name);
		if (mDbHelper.createEntry(category) > 0) {
			Toast.makeText(this, String.format(getString(R.string.category_was_created), category.getName()), Toast.LENGTH_LONG).show();
		}

		CategoryList.loadAll(mDbHelper);
		fillCategoryData();
		checkTexts();
	};

	@Override
	protected void processAddNewItem(String name, long parentId) {
		final Subcategory subcategory = new Subcategory();
		subcategory.setName(name);
		subcategory.setParentId(parentId);
		if (mDbHelper.createEntry(subcategory) > 0) {
			Toast.makeText(this, String.format(getString(R.string.subcategory_was_created), subcategory.getName()), Toast.LENGTH_LONG).show();
		}
		CategoryList.loadAll(mDbHelper);
		fillCategoryData();
		checkTexts();
	}

	@Override
	protected void processDeleteItem(IStorable item) {
		if (item.getClass() == Category.class) {
			final Category category = (Category) item;
			if (category != null) {
				if (mDbHelper.deleteEntry(category)) {
					Toast.makeText(this, String.format(getString(R.string.category_was_deleted), category.getName()), Toast.LENGTH_LONG).show();
				}
			}
		}

		if (item.getClass() == Subcategory.class) {
			final Subcategory subcategory = (Subcategory) item;
			if (subcategory != null) {
				// delete all subcategory payments
				mDbHelper.deleteEntries(new Payment(), DbAdapter.PAYMENT_CATEGORY + "=" + subcategory.getId());
				if (mDbHelper.deleteEntry(subcategory)) {
					Toast.makeText(this, String.format(getString(R.string.subcategory_was_deleted), subcategory.getName()), Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(this, getString(R.string.error_database_error), Toast.LENGTH_LONG).show();
				}
			}
		}

		Repeating.deleteUnused(mDbHelper);
		CategoryList.loadAll(mDbHelper);
		fillCategoryData();
		checkTexts();
	}

	@Override
	protected void processEditItem(IStorable item, String name) {
		if (item.getClass() == Category.class) {
			final Category category = (Category) item;
			category.setName(name);
			if (mDbHelper.updateEntry(category)) {
				Toast.makeText(this, String.format(getString(R.string.category_was_changed), category.getName()), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, String.format(getString(R.string.error_database_error), category.getName()), Toast.LENGTH_LONG).show();
			}
		}
		if (item.getClass() == Subcategory.class) {
			final Subcategory subcategory = (Subcategory) item;
			if (subcategory != null) {
				subcategory.setName(name);
				if (mDbHelper.updateEntry(subcategory)) {
					Toast.makeText(this, String.format(getString(R.string.subcategory_was_changed), subcategory.getName()), Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(this, String.format(getString(R.string.error_database_error), subcategory.getName()), Toast.LENGTH_LONG).show();
				}
			}
		}

		CategoryList.loadAll(mDbHelper);
		fillCategoryData();
		// categoriesListView.expandGroup(groupPos)
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	public void checkTexts() {
	}
}
